package com.geek.factory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.factory.dto.ProductInStockDTO;
import com.geek.factory.entity.ProductStock;
import com.geek.factory.mapper.ProductStockMapper;
import com.geek.factory.service.ProductStockService;
import org.springframework.stereotype.Service;

@Service
public class ProductStockServiceImpl  extends ServiceImpl<ProductStockMapper, ProductStock> implements ProductStockService {
    @Override
    public void increaseStock(int productId, int quantity) {
        // 判断是否已有库存记录
        QueryWrapper<ProductStock> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        ProductStock stock = this.getOne(wrapper);

        if (stock == null) {
            // 没有则新增
            ProductStock newStock = new ProductStock();
            newStock.setProductId(Math.toIntExact(productId));
            newStock.setQuantity(quantity);
            this.save(newStock);
        } else {
            // 有则更新数量
            stock.setQuantity(stock.getQuantity() + quantity);
            this.updateById(stock);
        }
    }


    @Override
    public ProductStock getByProductId(int productId) {
        QueryWrapper<ProductStock> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        return this.getOne(wrapper);

    }

}
